package com.wingscode.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.R;
import com.wingscode.modules.app.form.ChatForm;
import com.wingscode.modules.common.entity.*;
import com.wingscode.modules.common.service.*;
import com.wingscode.modules.sys.controller.AbstractController;
import com.wingscode.modules.sys.entity.InquiryEntity;
import com.wingscode.modules.sys.entity.OfferPriceEntity;
import com.wingscode.modules.sys.service.InquiryService;
import com.wingscode.modules.sys.service.OfferPriceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 消息
 *
 * @author yan
 */
@RestController
@RequestMapping("/app/1")
@Api("消息")
public class AppController1 extends AbstractController {
    @Autowired
    private ChatObjectService chatObjectService;
    @Autowired
    private ChatDetailService chatDetailService;
    @Autowired
    private InquiryService inquiryService;
    @Autowired
    private OfferPriceService offerPriceService;


    @PostMapping("/chat")
    @ApiOperation("立即沟通-聊天")
    public R chat(@RequestBody ChatForm form) {
        if (form.getContentType() == null)
            return R.error("contentType为空");
        if ((form.getContent() == null || form.getContent().isEmpty())
                && (form.getImgUrl() == null || form.getImgUrl().isEmpty()))
            return R.error("content或imgUrl为空");
        if (form.getChatId() == null)
            return R.error("chatId为空");

        // 查询当前聊天对象是否存在
        ChatObjectEntity chatObject = chatObjectService.getById(form.getChatId());
        ChatDetailEntity chatDetail = new ChatDetailEntity();

        // 判断当前聊天内容为文字，还是文件/图片
        if (form.getContentType() == 0) {
            chatObject.setLastContent(form.getContent());
            chatDetail.setContent(form.getContent());
        } else {
            chatObject.setLastImg(form.getImgUrl());
            chatDetail.setImgUrl(form.getImgUrl());
        }
        chatObject.setLastTime(new Date());

        if (chatObject != null && chatObject.getId() != null) {
            // 存在，更新最新聊天对象信息
            chatObject.setState(1);
            chatObjectService.updateById(chatObject);

//            // 更新所有聊天内容为已读
//            ChatDetailEntity detail = new ChatDetailEntity();
//            detail.setIsRead(1);
//            detail.setChatId(chatObject.getId());
//            if (chatObject.getFromAgentId() == form.getAgentId()) {
//                // 更新接收方信息为已读
//                detail.setToAgentId(chatObject.getToAgentId());
//                chatDetailService.updateByToAgent(detail);
//            } else {
//                // 更新发起方信息为已读
//                detail.setFromAgentId(chatObject.getFromAgentId());
//                chatDetailService.updateByFromAgent(detail);
//            }
        } else {
            // 不存在，添加最新聊天对象信息
            chatObject.setState(0);
            chatObject.setType(form.getType());
            chatObject.setInquiryId(form.getInquiryId());

            chatObjectService.save(chatObject);
        }

        // 保存聊天内容
        if (chatObject.getFromAgentId() != null && chatObject.getFromAgentId() == form.getAgentId()) {
            chatDetail.setFromAgentId(chatObject.getFromAgentId());
            chatDetail.setFromUserId(chatObject.getFromUserId());
        }
        if (chatObject.getToAgentId() != null && chatObject.getToAgentId() == form.getAgentId()) {
            chatDetail.setToAgentId(chatObject.getToAgentId());
            chatDetail.setToUserId(chatObject.getToUserId());
        }
        chatDetail.setChatId(chatObject.getId());
        chatDetail.setCreateTime(new Date());
        chatDetail.setIsRead(0);
        chatDetail.setType(form.getContentType());

        chatDetailService.save(chatDetail);

        return R.ok();
    }

    @PostMapping("/getChatDetail")
    @ApiOperation("获得聊天消息")
    public R getChatDetail(@RequestBody ChatForm chatForm) {
        ChatObjectEntity chatObject = new ChatObjectEntity();

        if (chatForm.getIsInquiry() == null)
            return R.error("isInquiry为空");
        if (chatForm.getIsInquiry() == 0 && chatForm.getChatId() == null)
            return R.error("chatId为空");
        if (chatForm.getIsInquiry() == 1 && chatForm.getOfferPriceId() == null)
            return R.error("offerPriceId为空");

        // 获得招标信息
        InquiryEntity inquiry = inquiryService.getById(chatForm.getInquiryId());

        // 消息列表沟通
        if (chatForm.getIsInquiry() == 0) {
            chatObject = chatObjectService.getById(chatForm.getChatId());
            if (chatObject != null) {
                // 聊天发起方企业id == 当前登录企业id，为聊天发起方
                if (chatObject.getFromAgentId() == chatForm.getAgentId())
                    chatObject.setFromUserId(chatForm.getUserId());
                else
                    // 否则，为聊天接收方
                    chatObject.setToUserId(chatForm.getUserId());
            }
        } else if (chatForm.getIsInquiry() == 1){
            // 我的招标沟通、我的报价沟通
            // 报价信息
            OfferPriceEntity offerPrice = offerPriceService.getById(chatForm.getOfferPriceId());
            List<ChatObjectEntity> chatList = chatObjectService.list(
                    new QueryWrapper<ChatObjectEntity>()
                            .eq("inquiry_id", chatForm.getInquiryId())
                            .and(
                                    Wrapper -> Wrapper.eq("from_agent_id", inquiry.getAgentId())
                                            .or().eq("to_agent_id", offerPrice.getAgentId())
                            )
                            .and(
                                    Wrapper -> Wrapper.eq("from_user_id", chatForm.getUserId())
                                            .or().eq("to_user_id", chatForm.getUserId())
                            )
            );
            if (chatList != null && chatList.size() > 0)
                chatObject = chatList.get(0);

            chatObject.setFromAgentId(inquiry.getAgentId());
            chatObject.setToAgentId(offerPrice.getAgentId());
            if (inquiry.getAgentId() == chatForm.getAgentId()) {
                chatObject.setFromUserId(chatForm.getUserId());
                chatObject.setToUserId(offerPrice.getUserId());
            } else {
                chatObject.setToUserId(chatForm.getUserId());
                chatObject.setFromUserId(inquiry.getUserId());
            }
        } else if (chatForm.getIsInquiry() == 2) {
            // 市场供应沟通
            List<ChatObjectEntity> chatList = chatObjectService.list(
                    new QueryWrapper<ChatObjectEntity>()
                            .eq("inquiry_id", chatForm.getInquiryId())
                            .and(
                                    Wrapper -> Wrapper.eq("from_agent_id", chatForm.getAgentId())
                                            .or().eq("to_agent_id", inquiry.getAgentId())
                            )
                            .and(
                                    Wrapper -> Wrapper.eq("from_user_id", chatForm.getUserId())
                                            .or().eq("to_user_id", chatForm.getUserId())
                            )
            );
            if (chatList != null && chatList.size() > 0)
                chatObject = chatList.get(0);

            chatObject.setFromAgentId(chatForm.getAgentId());
            chatObject.setToAgentId(inquiry.getAgentId());
            if (inquiry.getAgentId() == chatForm.getAgentId()) {
                chatObject.setToUserId(chatForm.getUserId());
            } else {
                chatObject.setFromUserId(chatForm.getUserId());
                chatObject.setToUserId(inquiry.getUserId());
            }
        } else if (chatForm.getIsInquiry() == 3) {
            // 平台沟通
            List<ChatObjectEntity> chatList = chatObjectService.list(
                    new QueryWrapper<ChatObjectEntity>()
                            .eq("inquiry_id", chatForm.getInquiryId())
                            .eq("from_agent_id", chatForm.getAgentId())
                            .isNull("to_agent_id")
                            .eq("from_user_id", chatForm.getUserId())
            );
            if (chatList != null && chatList.size() > 0)
                chatObject = chatList.get(0);

            chatObject.setFromAgentId(chatForm.getAgentId());
            chatObject.setFromUserId(chatForm.getUserId());
            chatObject.setType(1);
        }

        if (chatObject == null || chatObject.getId() == null) {
            chatObject.setState(0);
            chatObject.setType(chatForm.getType());
            chatObject.setInquiryId(chatForm.getInquiryId());

            chatObjectService.save(chatObject);
        } else if (chatObject != null && chatObject.getId() != null) {
            // 存在，更新所有聊天内容为已读
            ChatDetailEntity detail = new ChatDetailEntity();
            detail.setIsRead(1);
            detail.setChatId(chatObject.getId());
            if (chatObject.getToAgentId() == null) {
                // 更新平台信息为已读
                chatDetailService.updateByToUserId(detail);
            } else if (chatObject.getFromAgentId() == chatForm.getAgentId()) {
                // 更新接收方信息为已读
                detail.setToAgentId(chatObject.getToAgentId());
                chatDetailService.updateByToAgent(detail);
            } else {
                // 更新发起方信息为已读
                detail.setFromAgentId(chatObject.getFromAgentId());
                chatDetailService.updateByFromAgent(detail);
            }
        }

        Map<String, Object> params = new HashMap<>();
        params.put("page", chatForm.getPage());
        params.put("limit", chatForm.getLimit());
        params.put("chatId", chatObject.getId());
        PageUtils page = chatDetailService.getDetail(params);

        return R.ok(200, page, chatObject.getId());
    }

    @PostMapping("/chatList")
    @ApiOperation("消息列表")
    public R chatList(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId"))
            return R.error("userId为空");
        if (!params.containsKey("agentId"))
            return R.error("agentId为空");

        PageUtils page = chatObjectService.chatList(params);

        return R.ok(200, page);
    }

    @GetMapping("/deleteChatObject")
    @ApiOperation("删除聊天")
    public R deleteChatObject(@RequestParam Integer chatId) {
        if (chatId == null)
            return R.error("chatId为空");

        // 删除聊天对象
        chatObjectService.removeById(chatId);
        // 删除聊天信息
        chatDetailService.deleteByChatId(chatId);

        return R.ok();
    }

}
